package com.cyy.media.service.jobhandler;

import com.cyy.base.utils.Mp4VideoUtil;
import com.cyy.media.model.po.MediaProcess;
import com.cyy.media.service.MediaFileProcessService;
import com.cyy.media.service.MediaFileService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author cyy
 * @date 2025/2/11
 * @description VideoTask 视频处理类
 */
@Slf4j
@Component
public class VideoTask {

    @Autowired
    MediaFileProcessService mediaFileProcessService;

    @Autowired
    MediaFileService mediaFileService;

    @Value("${videoprocess.ffmpegpath}")
    private String ffmpegpath;

    /**
     * 视频处理任务
     */
    @XxlJob("videoJobHandler")
    public void videoJobHandler() throws Exception {
        // 分片参数
        int shardIndex = XxlJobHelper.getShardIndex();//执行器的序号，从0开始
        int shardTotal = XxlJobHelper.getShardTotal();//执行器总数
        //确认cpu的核心数
        int count = Runtime.getRuntime().availableProcessors();
        //查询待处理的任务
        List<MediaProcess> mediaProcessList = mediaFileProcessService.getMediaProcessList(shardIndex, shardTotal, count);
        //任务数量
        int size = mediaProcessList.size();
        log.debug("取到的视频任务数:{}", size);
        if (size <= 0) return;
        //创建一个线程池
        ExecutorService executorService = Executors.newFixedThreadPool(size);

        //使用计数器
        CountDownLatch countDownLatch = new CountDownLatch(size);

        mediaProcessList.forEach(mediaProcess -> {
            //将任务加入线程池
            executorService.execute(() -> {
                //任务执行逻辑
                Long taskId = mediaProcess.getId();
                //文件id就是md5
                String fileId = mediaProcess.getFileId();
                try {
                    //1. 开启任务
                    boolean b = mediaFileProcessService.startTask(taskId);
                    if (!b) {
                        log.debug("抢占任务失败，任务id:{}", taskId);
                        return;
                    }
                    String bucket = mediaProcess.getBucket();
                    String filePath = mediaProcess.getFilePath();
                    //2. 下载minio视频到本地
                    File file = mediaFileService.downloadFileFromMinio(bucket, filePath);
                    if (file == null) {
                        log.debug("下载视频出错， 任务id:{}, bucket:{}, objectName:{}", taskId, bucket, filePath);
                        //保存任务处理失败的结果
                        mediaFileProcessService.saveProcessFinishStatus(taskId, "3", fileId, null, "下载视频到本地出错");
                    }
                    //转换后mp4文件的路径
                    //3. 先创建临时文件
                    File mp4File = null;
                    try {
                        mp4File = File.createTempFile("minio", ".mp4");
                    } catch (IOException e) {
                        log.debug("创建临时文件异常, {}", e.getMessage());
                        mediaFileProcessService.saveProcessFinishStatus(taskId, "3", fileId, null, "创建临时文件异常");
                        return;
                    }
                    //4. 处理视频
                    String video_path = file.getAbsolutePath();
                    String mp4_name = fileId + ".mp4";
                    String mp4_path = mp4File.getAbsolutePath();
                    //创建工具类对象
                    Mp4VideoUtil videoUtil = new Mp4VideoUtil(ffmpegpath, video_path, mp4_name, mp4_path);
                    //开始视频转换
                    String result = videoUtil.generateMp4();
                    System.out.println(result);
                    if (!result.equals("success")) {
                        log.debug("视频转码失败，原因: {}, bucket:{}, objectName:{}", result, bucket, filePath);
                        mediaFileProcessService.saveProcessFinishStatus(taskId, "3", fileId, null, result);
                        return;
                    }
                    //将.mp4上传到minio
                    String objectName = getFilePathByMd5(fileId, ".mp4");
                    String url = "/" + bucket + "/" + objectName;
                    boolean b1 = mediaFileService.addMediaFilesMinio(mp4File.getAbsolutePath(), "video/mp4", bucket, objectName);
                    if (!b1) {
                        log.debug("视频上传到minio失败，原因: {}, bucket:{}, objectName:{}", result, bucket, objectName);
                        mediaFileProcessService.saveProcessFinishStatus(taskId, "3", fileId, null, "视频上传到minio失败");
                        return;
                    }
                    //保存任务处理
                    mediaFileProcessService.saveProcessFinishStatus(taskId, "2", fileId, url, null);
                } catch (Exception e) {
                    log.debug("操作失败，原因: {}", e.getMessage(), e);
                    mediaFileProcessService.saveProcessFinishStatus(taskId, "3", fileId, null, "处理后视频上传或入库失败");
                } finally {
                    countDownLatch.countDown();
                }
            });
        });
        //阻塞, 指定最大限制的等待时间
        countDownLatch.await(30, TimeUnit.MINUTES);

    }

    private String getFilePathByMd5(String fileMd5, String extend) {
        return fileMd5.substring(0, 1) + "/" + fileMd5.substring(1, 2) + "/" + fileMd5 + "/" + fileMd5 + extend;
    }


}
